//! 通用数据生成器模块
//! 提供各种类型数据的生成方法，供不同数据库填充器使用

use std::collections::HashMap;
use librarys::random_letters;
use serde_json::Value;
use crate::error::Result;
// 使用 data-forge 的核心生成能力
use crate::generation::DataForge;
use crate::db::schema::{TableSchema, FieldSchema, DataType, FieldGeneratorType};
// 导入需要的生成器模块
use crate::generators::{number, datetime, internet};


/// 通用数据生成器
pub struct GenericDataGenerator;

impl GenericDataGenerator {
    /// 根据表结构生成数据
    pub fn generate_data_by_schema(schema: &TableSchema, count: usize) -> Result<Vec<HashMap<String, Value>>> {
        let mut data = Vec::with_capacity(count);
        // 使用 data-forge 的核心生成能力
        let forge = DataForge::new(crate::generation::Language::ZhCN);
        
        for _ in 1..=count {
            let mut row = HashMap::new();
            
            for field in &schema.fields {
                let value = Self::generate_value_for_field(&forge, field)?;
                row.insert(field.name.clone(), value);
            }
            
            data.push(row);
        }
        
        Ok(data)
    }
    
    /// 根据字段类型和生成器类型生成值 - 复用 data-forge 的核心生成能力
    fn generate_value_for_field(forge: &DataForge, field: &FieldSchema) -> Result<Value> {
        // 首先检查是否有指定的生成器类型
        if let Some(generator_type) = &field.generator_type {
            return Self::generate_value_by_generator_type(forge, field, generator_type);
        }
        
        // 如果没有指定生成器类型，则根据数据类型自动生成
        match &field.data_type {
            DataType::String { max_length } => {
                let max_len = max_length.unwrap_or(255) as usize;
                let len = std::cmp::min(10, max_len);
                // 复用 data-forge 的随机字符串生成能力
                Ok(Value::String(random_letters(len)))
            },
            DataType::Integer { .. } => {
                // 复用 data-forge 的数字生成能力
                Ok(forge.generate("random_int").unwrap_or_else(|| {
                    Value::Number(serde_json::Number::from(crate::generators::random_int(0, 1000000)))
                }))
            },
            DataType::Float { .. } => {
                // 复用 data-forge 的浮点数生成能力
                Ok(forge.generate("random_float").unwrap_or_else(|| {
                    Value::Number(serde_json::Number::from_f64(crate::generators::random_float(0.0, 1000.0)).unwrap())
                }))
            },
            DataType::Boolean => {
                // 复用 data-forge 的布尔值生成能力
                Ok(forge.generate("random_bool").unwrap_or_else(|| {
                    Value::Bool(crate::generators::random_bool())
                }))
            },
            DataType::DateTime { .. } => {
                // 复用 data-forge 的日期时间生成能力
                Ok(forge.generate("datetime_now").unwrap_or_else(|| {
                    Value::String(crate::generators::datetime::iso8601())
                }))
            },
            DataType::Date { .. } => {
                // 复用 data-forge 的日期生成能力
                Ok(forge.generate("date_now").unwrap_or_else(|| {
                    Value::String(crate::generators::datetime::date_iso())
                }))
            },
            DataType::Email => {
                // 复用 data-forge 的邮箱生成能力
                Ok(forge.generate("email").unwrap_or_else(|| {
                    Value::String(crate::generators::internet::email())
                }))
            },
            DataType::Phone { .. } => {
                // 复用 data-forge 的电话号码生成能力
                Ok(forge.generate("phone_cn").unwrap_or_else(|| {
                    Value::String(crate::generators::number::phone_number_cn())
                }))
            },
            DataType::Url => {
                // 复用 data-forge 的URL生成能力
                Ok(forge.generate("url").unwrap_or_else(|| {
                    Value::String(crate::generators::internet::url())
                }))
            },
            DataType::Uuid => {
                // 复用 data-forge 的UUID生成能力
                Ok(forge.generate("uuid_v4").unwrap_or_else(|| {
                    Value::String(crate::generators::uuid_v4())
                }))
            },
            _ => {
                // 默认生成字符串值
                Ok(Value::String(random_letters(10)))
            }
        }
    }
    
    /// 根据指定的生成器类型生成值
    fn generate_value_by_generator_type(forge: &DataForge, field: &FieldSchema, generator_type: &FieldGeneratorType) -> Result<Value> {
        match generator_type {
            FieldGeneratorType::Default => {
                // 使用默认生成逻辑
                Self::generate_value_for_field(forge, field)
            },
            FieldGeneratorType::Custom(generator_name) => {
                // 使用自定义生成器
                Ok(forge.generate(generator_name).unwrap_or_else(|| {
                    Value::String(format!("custom_{}", generator_name))
                }))
            },
            FieldGeneratorType::RandomString => {
                let len = match &field.data_type {
                    DataType::String { max_length } => max_length.unwrap_or(10),
                    _ => 10,
                };
                Ok(Value::String(random_letters(len as usize)))
            },
            FieldGeneratorType::RandomInteger => {
                Ok(Value::Number(serde_json::Number::from(crate::generators::random_int(0, 1000000))))
            },
            FieldGeneratorType::RandomFloat => {
                Ok(Value::Number(serde_json::Number::from_f64(crate::generators::random_float(0.0, 1000.0)).unwrap()))
            },
            FieldGeneratorType::RandomBoolean => {
                Ok(Value::Bool(crate::generators::random_bool()))
            },
            FieldGeneratorType::CurrentTimestamp => {
                Ok(Value::String(crate::generators::datetime::iso8601()))
            },
            FieldGeneratorType::RandomDate => {
                Ok(Value::String(crate::generators::datetime::date_iso()))
            },
            FieldGeneratorType::RandomDateTime => {
                Ok(Value::String(crate::generators::datetime::iso8601()))
            },
            FieldGeneratorType::RandomEmail => {
                Ok(Value::String(crate::generators::internet::email()))
            },
            FieldGeneratorType::RandomPhone => {
                Ok(Value::String(crate::generators::number::phone_number_cn()))
            },
            FieldGeneratorType::RandomUrl => {
                Ok(Value::String(crate::generators::internet::url()))
            },
            FieldGeneratorType::Uuid => {
                Ok(Value::String(crate::generators::uuid_v4()))
            },
            FieldGeneratorType::Name => {
                // 根据语言设置生成相应语言的姓名
                match forge.language() {
                    crate::generation::Language::ZhCN => {
                        Ok(Value::String(crate::generators::name::zh_cn_fullname()))
                    },
                    crate::generation::Language::EnUS => {
                        Ok(Value::String(crate::generators::name::en_us_fullname()))
                    },
                    crate::generation::Language::JaJP => {
                        Ok(Value::String(crate::generators::name::ja_jp_fullname()))
                    },
                }
            },
            FieldGeneratorType::CompanyName => {
                Ok(Value::String(format!("Company {}", crate::generators::random_int(1, 1000))))
            },
            FieldGeneratorType::Address => {
                // 根据语言设置生成相应语言的地址
                match forge.language() {
                    crate::generation::Language::ZhCN => {
                        Ok(Value::String(format!("{}市{}区{}街道{}", 
                            crate::generators::address::zh_city(), 
                            crate::generators::address::zh_city(), 
                            crate::generators::random_int(1, 100),
                            crate::generators::random_int(1, 1000))))
                    },
                    crate::generation::Language::EnUS => {
                        Ok(Value::String(format!("{} Street {}, {}, {}", 
                            crate::generators::address::us_city(),
                            crate::generators::random_int(1, 1000),
                            crate::generators::address::us_city(),
                            crate::generators::address::us_state())))
                    },
                    crate::generation::Language::JaJP => {
                        Ok(Value::String(format!("{}{}{}丁目{}", 
                            crate::generators::address::us_city(),  // 使用us_city作为替代
                            crate::generators::address::us_city(),  // 使用us_city作为替代
                            crate::generators::random_int(1, 20),
                            crate::generators::random_int(1, 20))))
                    },
                }
            },
            FieldGeneratorType::ProductName => {
                let products = ["Laptop", "Smartphone", "Tablet", "Watch", "Headphones", "Speaker"];
                let product = products[crate::generators::random_int(0, products.len() as i32 - 1) as usize];
                Ok(Value::String(format!("{} {}", product, crate::generators::random_int(1, 1000))))
            },
            FieldGeneratorType::OrderStatus => {
                let statuses = ["Pending", "Processing", "Shipped", "Delivered", "Cancelled"];
                let status = statuses[crate::generators::random_int(0, statuses.len() as i32 - 1) as usize];
                Ok(Value::String(status.to_string()))
            },
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::db::schema::{FieldConstraints, DataType};

    #[test]
    fn test_person_field_generation_by_type() {
        // 创建一个人员表结构，基于字段类型而不是字段名
        let schema = TableSchema {
            name: "employees".to_string(),
            fields: vec![
                FieldSchema {
                    name: "id".to_string(),
                    data_type: DataType::Integer { min: None, max: None },
                    constraints: FieldConstraints {
                        nullable: false,
                        unique: true,
                        default: None,
                        pattern: None,
                        min: None,
                        max: None,
                    },
                    description: None,
                    generator_config: None,
                    generator_type: None,
                },
                FieldSchema {
                    name: "full_name".to_string(),
                    data_type: DataType::String { max_length: Some(100) },
                    constraints: FieldConstraints {
                        nullable: false,
                        unique: false,
                        default: None,
                        pattern: None,
                        min: None,
                        max: None,
                    },
                    description: None,
                    generator_config: None,
                    generator_type: None,
                },
                FieldSchema {
                    name: "birth_date".to_string(),
                    data_type: DataType::Date { format: None },
                    constraints: FieldConstraints {
                        nullable: false,
                        unique: false,
                        default: None,
                        pattern: None,
                        min: None,
                        max: None,
                    },
                    description: None,
                    generator_config: None,
                    generator_type: None,
                },
                FieldSchema {
                    name: "email_addr".to_string(),
                    data_type: DataType::Email,
                    constraints: FieldConstraints {
                        nullable: false,
                        unique: true,
                        default: None,
                        pattern: None,
                        min: None,
                        max: None,
                    },
                    description: None,
                    generator_config: None,
                    generator_type: None,
                },
            ],
            primary_key: Some(vec!["id".to_string()]),
            indexes: vec![],
            description: None,
        };

        // 生成数据
        let data = generate_person_data(&schema, 1).unwrap();
        assert_eq!(data.len(), 1);
        
        let row = &data[0];
        assert!(row.contains_key("id"));
        assert!(row.contains_key("full_name"));
        assert!(row.contains_key("birth_date"));
        assert!(row.contains_key("email_addr"));
        
        // 验证值类型正确
        assert!(row.get("id").unwrap().is_number());
        assert!(row.get("full_name").unwrap().is_string());
        assert!(row.get("birth_date").unwrap().is_string());
        assert!(row.get("email_addr").unwrap().is_string());
    }

    #[test]
    fn test_product_field_generation_by_type() {
        // 创建一个产品表结构，基于字段类型而不是字段名
        let schema = TableSchema {
            name: "products".to_string(),
            fields: vec![
                FieldSchema {
                    name: "product_identifier".to_string(),
                    data_type: DataType::Integer { min: None, max: None },
                    constraints: FieldConstraints {
                        nullable: false,
                        unique: true,
                        default: None,
                        pattern: None,
                        min: None,
                        max: None,
                    },
                    description: None,
                    generator_config: None,
                    generator_type: None,
                },
                FieldSchema {
                    name: "product_title".to_string(),
                    data_type: DataType::String { max_length: Some(100) },
                    constraints: FieldConstraints {
                        nullable: false,
                        unique: false,
                        default: None,
                        pattern: None,
                        min: None,
                        max: None,
                    },
                    description: None,
                    generator_config: None,
                    generator_type: None,
                },
                FieldSchema {
                    name: "unit_price".to_string(),
                    data_type: DataType::Float { min: None, max: None, precision: None },
                    constraints: FieldConstraints {
                        nullable: false,
                        unique: false,
                        default: None,
                        pattern: None,
                        min: None,
                        max: None,
                    },
                    description: None,
                    generator_config: None,
                    generator_type: None,
                },
            ],
            primary_key: Some(vec!["product_identifier".to_string()]),
            indexes: vec![],
            description: None,
        };

        // 生成数据
        let data = generate_product_data(&schema, 1).unwrap();
        assert_eq!(data.len(), 1);
        
        let row = &data[0];
        assert!(row.contains_key("product_identifier"));
        assert!(row.contains_key("product_title"));
        assert!(row.contains_key("unit_price"));
        
        // 验证值类型正确
        assert!(row.get("product_identifier").unwrap().is_number());
        assert!(row.get("product_title").unwrap().is_string());
        assert!(row.get("unit_price").unwrap().is_number());
    }

    #[test]
    fn test_table_type_detection() {
        // 创建一个人员表结构
        let person_schema = TableSchema {
            name: "users".to_string(),
            fields: vec![
                FieldSchema {
                    name: "user_id".to_string(),
                    data_type: DataType::Integer { min: None, max: None },
                    constraints: FieldConstraints::default(),
                    description: None,
                    generator_config: None,
                    generator_type: None,
                },
                FieldSchema {
                    name: "email_address".to_string(),
                    data_type: DataType::Email,
                    constraints: FieldConstraints::default(),
                    description: None,
                    generator_config: None,
                    generator_type: None,
                },
            ],
            primary_key: Some(vec!["user_id".to_string()]),
            indexes: vec![],
            description: None,
        };

        // 创建一个产品表结构
        let product_schema = TableSchema {
            name: "items".to_string(),
            fields: vec![
                FieldSchema {
                    name: "item_id".to_string(),
                    data_type: DataType::Integer { min: None, max: None },
                    constraints: FieldConstraints::default(),
                    description: None,
                    generator_config: None,
                    generator_type: None,
                },
                FieldSchema {
                    name: "item_name".to_string(),
                    data_type: DataType::String { max_length: Some(100) },
                    constraints: FieldConstraints::default(),
                    description: None,
                    generator_config: None,
                    generator_type: None,
                },
                FieldSchema {
                    name: "item_price".to_string(),
                    data_type: DataType::Float { min: None, max: None, precision: None },
                    constraints: FieldConstraints::default(),
                    description: None,
                    generator_config: None,
                    generator_type: None,
                },
            ],
            primary_key: Some(vec!["item_id".to_string()]),
            indexes: vec![],
            description: None,
        };

        // 测试类型检测
        assert!(is_person_table(&person_schema));
        assert!(is_product_table(&product_schema));
    }

    #[test]
    fn test_field_type_based_generation() {
        // 创建一个混合类型的表结构来测试完全基于字段类型的生成
        let schema = TableSchema {
            name: "mixed_table".to_string(),
            fields: vec![
                FieldSchema {
                    name: "any_integer_field".to_string(),
                    data_type: DataType::Integer { min: Some(0), max: Some(100) },
                    constraints: FieldConstraints::default(),
                    description: None,
                    generator_config: None,
                    generator_type: None,
                },
                FieldSchema {
                    name: "any_float_field".to_string(),
                    data_type: DataType::Float { min: Some(0.0), max: Some(100.0), precision: None },
                    constraints: FieldConstraints::default(),
                    description: None,
                    generator_config: None,
                    generator_type: None,
                },
                FieldSchema {
                    name: "any_string_field".to_string(),
                    data_type: DataType::String { max_length: Some(50) },
                    constraints: FieldConstraints::default(),
                    description: None,
                    generator_config: None,
                    generator_type: None,
                },
                FieldSchema {
                    name: "any_email_field".to_string(),
                    data_type: DataType::Email,
                    constraints: FieldConstraints::default(),
                    description: None,
                    generator_config: None,
                    generator_type: None,
                },
                FieldSchema {
                    name: "any_phone_field".to_string(),
                    data_type: DataType::Phone { country: None },
                    constraints: FieldConstraints::default(),
                    description: None,
                    generator_config: None,
                    generator_type: None,
                },
                FieldSchema {
                    name: "any_date_field".to_string(),
                    data_type: DataType::Date { format: None },
                    constraints: FieldConstraints::default(),
                    description: None,
                    generator_config: None,
                    generator_type: None,
                },
                FieldSchema {
                    name: "any_datetime_field".to_string(),
                    data_type: DataType::DateTime { format: None },
                    constraints: FieldConstraints::default(),
                    description: None,
                    generator_config: None,
                    generator_type: None,
                },
                FieldSchema {
                    name: "any_boolean_field".to_string(),
                    data_type: DataType::Boolean,
                    constraints: FieldConstraints::default(),
                    description: None,
                    generator_config: None,
                    generator_type: None,
                },
            ],
            primary_key: Some(vec!["any_integer_field".to_string()]),
            indexes: vec![],
            description: None,
        };

        // 生成数据
        let data = GenericDataGenerator::generate_data_by_schema(&schema, 1).unwrap();
        assert_eq!(data.len(), 1);
        
        let row = &data[0];
        assert!(row.contains_key("any_integer_field"));
        assert!(row.contains_key("any_float_field"));
        assert!(row.contains_key("any_string_field"));
        assert!(row.contains_key("any_email_field"));
        assert!(row.contains_key("any_phone_field"));
        assert!(row.contains_key("any_date_field"));
        assert!(row.contains_key("any_datetime_field"));
        assert!(row.contains_key("any_boolean_field"));
        
        // 验证值类型正确
        assert!(row.get("any_integer_field").unwrap().is_number());
        assert!(row.get("any_float_field").unwrap().is_number());
        assert!(row.get("any_string_field").unwrap().is_string());
        assert!(row.get("any_email_field").unwrap().is_string());
        assert!(row.get("any_phone_field").unwrap().is_string());
        assert!(row.get("any_date_field").unwrap().is_string());
        assert!(row.get("any_datetime_field").unwrap().is_string());
        assert!(row.get("any_boolean_field").unwrap().is_boolean());
    }

    /// 检查表是否为人员表 - 更多基于字段类型
    fn is_person_table(schema: &TableSchema) -> bool {
        let name_field_count = schema.fields.iter().filter(|field| {
            field.name.contains("name") || field.name.contains("first") || field.name.contains("last") ||
                field.name.contains("user") || field.name.contains("employee")
        }).count();

        let type_field_count = schema.fields.iter().filter(|field| {
            matches!(field.data_type, DataType::Email | DataType::Phone { .. })
        }).count();

        name_field_count > 1 || type_field_count > 0
    }

    /// 检查表是否为产品表 - 更多基于字段类型
    fn is_product_table(schema: &TableSchema) -> bool {
        let name_field_count = schema.fields.iter().filter(|field| {
            field.name.contains("name") || field.name.contains("title") || field.name.contains("sku")
        }).count();

        let price_field_count = schema.fields.iter().filter(|field| {
            field.name.contains("price") || field.name.contains("cost")
        }).count();

        let type_field_count = schema.fields.iter().filter(|field| {
            matches!(field.data_type, DataType::Float { .. } | DataType::Integer { .. }) &&
                (field.name.contains("price") || field.name.contains("cost") || field.name.contains("stock"))
        }).count();

        name_field_count > 0 || price_field_count > 0 || type_field_count > 0
    }

    /// 检查表是否为订单表 - 更多基于字段类型
    fn is_order_table(schema: &TableSchema) -> bool {
        let id_field_count = schema.fields.iter().filter(|field| {
            field.name.contains("order") || field.name.contains("customer")
        }).count();

        let amount_field_count = schema.fields.iter().filter(|field| {
            field.name.contains("amount") || field.name.contains("total")
        }).count();

        let type_field_count = schema.fields.iter().filter(|field| {
            matches!(field.data_type, DataType::Float { .. } | DataType::Integer { .. }) &&
                (field.name.contains("amount") || field.name.contains("total") || field.name.contains("quantity"))
        }).count();

        id_field_count > 0 || amount_field_count > 0 || type_field_count > 0
    }

    /// 检查表是否为公司表 - 更多基于字段类型
    fn is_company_table(schema: &TableSchema) -> bool {
        let name_field_count = schema.fields.iter().filter(|field| {
            field.name.contains("company") || field.name.contains("industry")
        }).count();

        let employee_field_count = schema.fields.iter().filter(|field| {
            field.name.contains("employee") || field.name.contains("founded")
        }).count();

        name_field_count > 0 || employee_field_count > 0
    }

    /// 检查表是否为地址表 - 更多基于字段类型
    fn is_address_table(schema: &TableSchema) -> bool {
        let address_field_count = schema.fields.iter().filter(|field| {
            field.name.contains("address") || field.name.contains("street") || field.name.contains("city") ||
                field.name.contains("province") || field.name.contains("state") || field.name.contains("postal") ||
                field.name.contains("zip")
        }).count();

        let type_field_count = schema.fields.iter().filter(|field| {
            matches!(field.data_type, DataType::Phone { .. }) && field.name.contains("phone")
        }).count();

        address_field_count > 1 || type_field_count > 0
    }

    /// 检查表是否为事件表 - 更多基于字段类型
    fn is_event_table(schema: &TableSchema) -> bool {
        let name_field_count = schema.fields.iter().filter(|field| {
            field.name.contains("event") || field.name.contains("name") || field.name.contains("title")
        }).count();

        let type_field_count = schema.fields.iter().filter(|field| {
            field.name.contains("type") || field.name.contains("description")
        }).count();

        let time_field_count = schema.fields.iter().filter(|field| {
            matches!(field.data_type, DataType::DateTime { .. } | DataType::Date { .. }) &&
                (field.name.contains("timestamp") || field.name.contains("date"))
        }).count();

        name_field_count > 0 || type_field_count > 0 || time_field_count > 0
    }

    /// 生成产品数据 - 基于表结构
    pub fn generate_product_data(schema: &TableSchema, count: usize) -> Result<Vec<HashMap<String, Value>>> {
        let forge = DataForge::new(crate::generation::Language::ZhCN);
        let mut data = Vec::with_capacity(count);
        for i in 1..=count {
            let mut row = HashMap::new();

            for field in &schema.fields {
                let value = generate_product_field_value(&forge, field, i)?;
                row.insert(field.name.clone(), value);
            }

            data.push(row);
        }
        Ok(data)
    }

    /// 生成产品相关字段的值 - 基于字段类型和生成器类型
    fn generate_product_field_value(forge: &DataForge, field: &FieldSchema, index: usize) -> Result<Value> {
        // 首先检查是否有指定的生成器类型
        if let Some(generator_type) = &field.generator_type {
            return GenericDataGenerator::generate_value_by_generator_type(forge, field, generator_type);
        }

        // 如果没有指定生成器类型，则根据字段名和数据类型生成
        match &field.data_type {
            DataType::String { max_length } => {
                let max_len = max_length.unwrap_or(255) as usize;
                if field.name.contains("name") || field.name.contains("title") || field.name.contains("product") {
                    let products = ["Laptop", "Smartphone", "Tablet", "Watch", "Headphones", "Speaker"];
                    let product = products[number::random_int(0, products.len() as i32 - 1) as usize];
                    Ok(Value::String(format!("{} {}", product, index)))
                } else if field.name.contains("description") {
                    Ok(Value::String(format!("Description for product {}", index)))
                } else if field.name.contains("sku") {
                    Ok(Value::String(format!("SKU-{:06}", index)))
                } else {
                    // 通用字符串
                    let len = std::cmp::min(10, max_len);
                    Ok(Value::String(random_letters(len)))
                }
            },
            DataType::Integer { min, max } => {
                let min_val = min.unwrap_or(0);
                let max_val = max.unwrap_or(1000000);
                if field.name.contains("stock") {
                    Ok(Value::Number(serde_json::Number::from(number::random_int(0, 1000))))
                } else {
                    // 通用整数
                    Ok(Value::Number(serde_json::Number::from(number::random_int(min_val as i32, max_val as i32))))
                }
            },
            DataType::Float { .. } => {
                if field.name.contains("price") || field.name.contains("cost") {
                    Ok(Value::Number(serde_json::Number::from_f64(number::random_float(10.0, 1000.0)).unwrap()))
                } else {
                    Ok(Value::Number(serde_json::Number::from_f64(number::random_float(0.0, 100.0)).unwrap()))
                }
            },
            DataType::Boolean => {
                Ok(Value::Bool(rand::random()))
            },
            DataType::DateTime { .. } | DataType::Date { .. } => {
                Ok(Value::String(datetime::iso8601()))
            },
            _ => {
                // 默认生成字符串值
                Ok(Value::String(random_letters(10)))
            }
        }
    }

    /// 生成人员数据（员工、用户等）- 基于表结构
    pub fn generate_person_data(schema: &TableSchema, count: usize) -> Result<Vec<HashMap<String, Value>>> {
        // 使用 data-forge 的核心生成能力
        let forge = DataForge::new(crate::generation::Language::ZhCN);

        let mut data = Vec::with_capacity(count);
        for i in 1..=count {
            let mut row = HashMap::new();

            for field in &schema.fields {
                let value = generate_person_field_value(&forge, field, i)?;
                row.insert(field.name.clone(), value);
            }

            data.push(row);
        }
        Ok(data)
    }

    /// 生成人员相关字段的值 - 基于字段类型和生成器类型
    fn generate_person_field_value(forge: &DataForge, field: &FieldSchema, _index: usize) -> Result<Value> {
        // 首先检查是否有指定的生成器类型
        if let Some(generator_type) = &field.generator_type {
            return GenericDataGenerator::generate_value_by_generator_type(forge, field, generator_type);
        }

        // 如果没有指定生成器类型，则根据字段名和数据类型生成
        match &field.data_type {
            DataType::String { max_length } => {
                let max_len = max_length.unwrap_or(255) as usize;
                if field.name.contains("name") || field.name.contains("user") || field.name.contains("employee") {
                    // 根据语言设置生成相应语言的姓名
                    match forge.language() {
                        crate::generation::Language::ZhCN => {
                            Ok(Value::String(crate::generators::name::zh_cn_fullname()))
                        },
                        crate::generation::Language::EnUS => {
                            Ok(Value::String(crate::generators::name::en_us_fullname()))
                        },
                        crate::generation::Language::JaJP => {
                            Ok(Value::String(crate::generators::name::ja_jp_fullname()))
                        },
                    }
                } else if field.name.contains("email") {
                    Ok(Value::String(crate::generators::internet::email()))
                } else if field.name.contains("phone") {
                    Ok(Value::String(crate::generators::number::phone_number_cn()))
                } else {
                    // 通用字符串
                    let len = std::cmp::min(10, max_len);
                    Ok(Value::String(random_letters(len)))
                }
            },
            DataType::Integer { min, max } => {
                let min_val = min.unwrap_or(0);
                let max_val = max.unwrap_or(1000000);
                if field.name.contains("age") {
                    Ok(Value::Number(serde_json::Number::from(number::random_int(18, 65))))
                } else if field.name.contains("salary") || field.name.contains("wage") {
                    Ok(Value::Number(serde_json::Number::from(number::random_int(3000, 50000))))
                } else {
                    // 通用整数
                    Ok(Value::Number(serde_json::Number::from(number::random_int(min_val as i32, max_val as i32))))
                }
            },
            DataType::Float { .. } => {
                if field.name.contains("salary") || field.name.contains("wage") {
                    Ok(Value::Number(serde_json::Number::from_f64(number::random_float(3000.0, 50000.0)).unwrap()))
                } else {
                    Ok(Value::Number(serde_json::Number::from_f64(number::random_float(0.0, 100.0)).unwrap()))
                }
            },
            DataType::Boolean => {
                Ok(Value::Bool(rand::random()))
            },
            DataType::DateTime { .. } | DataType::Date { .. } => {
                if field.name.contains("birth") {
                    Ok(Value::String(datetime::birthday()))
                } else {
                    Ok(Value::String(datetime::iso8601()))
                }
            },
            DataType::Email => {
                Ok(Value::String(crate::generators::internet::email()))
            },
            DataType::Phone { .. } => {
                Ok(Value::String(crate::generators::number::phone_number_cn()))
            },
            _ => {
                // 默认生成字符串值
                Ok(Value::String(random_letters(10)))
            }
        }
    }

}